package com.cbtx.networklib.interceptor

import com.cbtx.networklib.constant.TagConstant.MJ_REQUEST
import com.cbtx.networklib.constant.TagConstant.MJ_RESPONSE
import com.cbtx.networklib.log.LogBuilder
import com.cbtx.networklib.log.Logger
import com.cbtx.networklib.log.Printer
import okhttp3.FormBody
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
import okhttp3.internal.platform.Platform
import okhttp3.logging.HttpLoggingInterceptor
import java.io.IOException

/**
 * author : joker.peng
 * e-mail : joker@fiture.com
 * date   : 2021/7/1 9:50 AM
 * desc   :
 */
class LogInterceptor(var isOpenLog: Boolean = true, var prettyJsonPrinting: Boolean = true) : Interceptor {

    companion object {

        //日志拦截器默认日志打印工具
        private val LOGGER: Logger = object : Logger {
            override fun log(level: Int, tag: String?, msg: String?) {
//                LogUtil.d(tag, msg)
            }
        }
        private const val ERROR_DECRYPT_MSG = "解密失败"
    }

    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {

        val request = chain.request()
        // debug 才允许打印（release 的 apk 每次都会创建对象，如果存在大量的 log 则在低端手机会导致 OOM）
        if (isOpenLog) {
            Printer.printJsonRequest(
                LogBuilder() //是否开启日志打印
                    .loggable(isOpenLog) //打印的等级
                    .setLevel(HttpLoggingInterceptor.Level.BASIC) // 打印类型
                    .log(Platform.INFO)
//                    .logger(LOGGER) // request的Tag
                    .prettyJsonPrinting(prettyJsonPrinting)
                    .request(MJ_REQUEST) // Response的Tag
                    .response("Response") // 添加打印头, 注意 key 和 value 都不能是中文
                    .addHeader("log-header", "log header"), request
            )
        }

        val response =  chain.proceed(request)
        val result: String = response.body!!.string()
        var extraLogInfo: String = request.url.toString()
        if (isOpenLog) {
            Printer.printJsonResponse(
                LogBuilder() //是否开启日志打印
                    .loggable(isOpenLog)
                    .setLevel(HttpLoggingInterceptor.Level.BASIC) // 打印类型
                    .log(Platform.INFO)
//                    .logger(LOGGER)
                    .prettyJsonPrinting(prettyJsonPrinting)
                    .response(MJ_RESPONSE)
                    .addHeader("log-header", "log header"), extraLogInfo,
                result
            )
        }
        if (result == null) {
            response.close()
            throw IOException(ERROR_DECRYPT_MSG)
        }
        val newResponse = response.newBuilder().body(
            okhttp3.ResponseBody.create(
                response.body?.contentType(), result
            )
        ).build()
        response.close()
        return newResponse
    }
}